﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections;
using System.Web.Caching;

namespace TheOutfield.UmbExt.UniversalMediaPicker
{
    public class UniversalMediaPickerCache
    {
        private static System.Web.Caching.Cache cache;

        static UniversalMediaPickerCache()
        {
            cache = HttpContext.Current.Cache;
        }

        public static void Set(string cache_key, object cache_object, DateTime expiration)
        {
            Set(cache_key, cache_object, expiration, CacheItemPriority.Normal);
        }

        public static void Set(string cache_key, object cache_object, TimeSpan expiration)
        {
            Set(cache_key, cache_object, expiration, CacheItemPriority.Normal);
        }

        public static void Set(string cache_key, object cache_object, DateTime expiration, CacheItemPriority priority)
        {
            cache.Insert(cache_key, cache_object, null, expiration,
                System.Web.Caching.Cache.NoSlidingExpiration,
                priority, null);
        }

        public static void Set(string cache_key, object cache_object, TimeSpan expiration, CacheItemPriority priority)
        {
            cache.Insert(cache_key, cache_object, null,
                System.Web.Caching.Cache.NoAbsoluteExpiration,
                expiration, priority, null);
        }

        public static T Get<T>(string key) where T : class
        {
            return cache.Get(key) as T;
        }

        public static List<string> GetCacheKeys()
        {
            List<string> keys = new List<string>();
            IDictionaryEnumerator ca = cache.GetEnumerator();
            while (ca.MoveNext())
            {
                keys.Add(ca.Key.ToString());
            }
            return keys;
        }

        public static bool Exists(string cache_key)
        {
            if (cache[cache_key] != null)
                return true;
            else
                return false;
        }

        public static void Delete(string cache_key)
        {
            if (Exists(cache_key))
                cache.Remove(cache_key);
        }

        public static void Flush()
        {
            foreach (string s in GetCacheKeys())
            {
                Delete(s);
            }
        }

        public static void Flush(string startsWith)
        {
            foreach (string s in GetCacheKeys())
            {
                if(s.StartsWith(startsWith))
                    Delete(s);
            }
        }

        // TODO: Add flush method with starts with string, to allow flushing of single control
    }
}